<?php
namespace app\index\controller;
use think\Controller;
use think\Request;
use think\Db;
class Index extends Controller
{
    public function index(){
        return view('index');
    }

    //添加学生信息
    public function add(){
        $name = Request::instance()->get('name');
        $sex  = Request::instance()->get('sex');
        $sfz  = Request::instance()->get('sfz');
        $cid  = Request::instance()->get('cid');

        $res  = Db::execute("insert into student values('','$name','$sex','$sfz','$cid',1)");

        if ($res){
            $this->success('添加成功','index/show','','1');
        }
    }

    //展示学生信息
    public function show(){
        $where = "1=1";

        if (!empty($_GET['search'])){
            $search = $_GET['search'];
            $where .= " and name like '%$search%'";
            $count  = Db::query("select count(*) as num from student where $where");
        }else{
            $count  = Db::query("select count(*) as num from student");
        }

        $size   = 3;

        if (!empty($_GET['page'])){
            $page = $_GET['page'];
        }else{
            $page = 1;
        }

        $count  = $count[0]['num'];
        $last   = ceil($count/$size);
        $offset = ($page-1)*$size;
        $up     = $page-1<0?$page:$page-1;
        $next   = $page+1>$last?$page:$page+1;

        $data = Db::query("select * from student where $where LIMIT $offset,$size");

        $arr    = [
            'data'=>$data,
            'up'  =>$up,
            'next'=>$next,
            'last'=>$last
        ];

        if (Request::instance()->isAjax()){
            return $arr;
        }else{
            return view('show',[
                'data'=>$data,
                'up'  =>$up,
                'next'=>$next,
                'last'=>$last
            ]);
        }
    }

    //姓名及点及改
    public function edit(){
        $name = $_GET['name'];
        $sid   = $_GET['id'];
        $res  = Db::execute("update student set name = '$name' where sid = $sid");
    }


    //删除
    public function del(){

        $id = $_GET['id'];
        $res = Db::execute("delete from student where sid = $id");
        if ($res) {
            return 1;
        }
    }
}
